from alipay import AliPay
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework import mixins, status, request
from rest_framework import viewsets
from rest_framework.decorators import action

from drf_yasg.utils import swagger_auto_schema

from api.utils.common import with_common_response
from django.db.models import ObjectDoesNotExist
from api.models.user import User
from api.models.order import Order
from api.models.payment import Payment, Payrecord

from api.utils.common.db import paginate_list
from api.exceptions import ResourceNotFound
from api.auth import JWTAuthentication
from .serializer import PaymentBodySerializer, PaymentQuerySerializer, PaymentRecordSerializer


class UserPaymentVeiwSet(viewsets.ViewSet):
    permission_classes = [JWTAuthentication]

    @swagger_auto_schema(
        operation_summary="支付宝接口",
        operation_description="支付宝接口",
        responses=with_common_response({status.HTTP_200_OK: PaymentBodySerializer}),
    )
    @action(methods=["put"], url_path="app-pay", url_name="app-pay", detail=True)
    def app_pay(self, request, pk):
        try:
            order = Order.objects.get(order_num=pk, user=request.user.id)
        except ObjectDoesNotExist:
            raise ResourceNotFound(detail="未找到订单")

        # 拿到支付宝参数
        payment = Payment.objects.filter().first()
        if not payment:
            raise ResourceNotFound(detail="未找到支付参数")

        # 生成支付宝对象
        alipay = AliPay(
            appid=payment.appid,
            app_notify_url=None,
            app_private_key_string=payment.app_key,
            alipay_public_key_string=payment.ali_key,
            sign_type="RSA2",
            debug=payment.app_debug,
        )

        # 拿到支付链接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order.order_num,
            total_amount=str(order.total_rmb),
            subject="django_shop_%s" % order.order_num,
            return_url=payment.alipay_return_url,
        )

        response = PaymentBodySerializer({"alipay_url": payment.alipay_url + "?" + order_string})

        return Response(status=status.HTTP_202_ACCEPTED, data=response.data)

    @swagger_auto_schema(
        operation_summary="支付宝回调接口",
        operation_description="支付宝回调接口",
        query_serializer=PaymentQuerySerializer,
        responses=with_common_response({status.HTTP_200_OK: PaymentRecordSerializer}),
    )
    @action(methods=["get"], url_path="pay-callback", url_name="pay-callback", detail=False)
    def pay_callback(self, request):
        serializer = PaymentQuerySerializer(data=request.GET)
        serializer.is_valid(raise_exception=True)
        order_id = serializer.validated_data.get("out_trade_no")
        trade_id = serializer.validated_data.get("trade_no")
        signature = serializer.validated_data.pop("sign")

        payment = Payment.objects.first()
        if payment:
            raise ResourceNotFound(detail="未找到信息")

        alipay = AliPay(
            appid=payment.appid,
            app_notify_url=None,
            app_private_key_path=payment.app_key,
            alipay_public_key_path=payment.ali_key,
            sign_type="RSA2",
            debug=payment.app_debug,
        )
        if not alipay.verify(serializer.validated_data, signature):
            raise ValueError

        try:
            order = Order.objects.get(id=order_id)
        except ObjectDoesNotExist as e:
            raise ResourceNotFound(detail="未找到订单")
        if all([order_id, trade_id]):
            payrecord = Payrecord.objects.create(order=order, trade_num=trade_id)
        else:
            raise ValueError("参数缺失")

        response = PaymentRecordSerializer(payrecord)

        return Response(status=status.HTTP_201_CREATED, data=response.data)
